<template>
  <el-dialog append-to-body v-model="dialogVisible" title="上传图片" width="950px" @close="dialogVisible = false">
    <el-form ref="postForm" label-width="80px" class="ruleForm" :model="form" :rules="rules">
      <el-form-item label="分类：">
        <el-col :span="22">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="封面：" >
        <el-col :span="22">
          <el-upload ref="uploadRef" action="#" :class="{'upload-max': form.cover.length > 0}" accept="image/jpeg,image/gif,image/png,image/bmp" :auto-upload="false" list-type="picture-card" :limit="1" :on-change="changeCoverChange" :on-preview="handleCoverView" :on-remove="handleCoverRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-image-viewer v-if="dialogImageVisible" :url-list="[dialogImageUrl]" @close="dialogImageVisible = false" />
        </el-col>
      </el-form-item>
      <el-form-item label="视频：" required>
        <el-col :span="22">
          <el-upload ref="videoUploadRef" show-word-limit list-type="picture-card" accept="video/mp4,video/3gp" :class="{'upload-max' : form.video.length > 0}" :file-list="form.video" :on-change="changeVideoChange" action="#" multiple :limit="1" :auto-upload="false">
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <video :src="file.url" :autoplay="true"></video>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-delete" @click="handleVideoView(file)"><el-icon><View /></el-icon></span>
                <span class="el-upload-list__item-delete" @click="handleVideoRemove"><el-icon><Delete /></el-icon></span>
              </span>
            </template>
          </el-upload>
          <div class="el-upload__tip">
            视频大小不超过30M，支持mp4,3gp格式
          </div>
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button v-if="isSubmit" disabled :icon="Loading" type="primary">确定</el-button>
      <el-button v-else type="primary" @click="handleSave()">确定</el-button>
    </span>
    </template>
  </el-dialog>
  <el-dialog  width="600px" v-model="dialogVideoVisible">
    <video style="max-width:560px" controls :src="dialogVideoUrl" :autoplay="true"></video>
  </el-dialog>
</template>
<script lang="ts" setup>
import { Plus,Loading,Delete,View } from '@element-plus/icons-vue'
import type { UploadProps, UploadFile, UploadFiles } from 'element-plus'
import { ElMessage } from 'element-plus'
import {ref,reactive, computed,watch } from 'vue'
import {FileCategorys, UploadVideo} from '@/api/file'
import { FileType } from '@/utils/enum'

/** 查看图片 */
const dialogImageVisible = ref<boolean>(false)
/** 查看图片地址 */
const dialogImageUrl = ref<string>('')
/** 查看视频弹窗 */
const dialogVideoVisible = ref<boolean>(false)
/** 查看视频地址 */
const dialogVideoUrl = ref<string>('')
/** 分类列表 */
const categorys = ref<any>([])
 /** 是否提交 */
const isSubmit = ref<boolean>(false)

const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    category: {
      type: Number,
      default: 0
    }
})
const form = ref<UploadVideoCommand>({
  video: [],
  cover: [],
  category: props.category,

})

const rules = reactive({
  video: [{ required: true, message: '请上传视频', trigger: 'blur' }]
})

/** 
 * 查看封面图片
 */
const handleCoverView: UploadProps['onPreview'] = (uploadFile:UploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogImageVisible.value = true
}
/** 
 * 查看视频图片
 */
 const handleVideoView: UploadProps['onPreview'] = (uploadFile:UploadFile) => {

  dialogVideoUrl.value = uploadFile.url!
  dialogVideoVisible.value = true
}
/**
 * 修改封面
 */
const changeCoverChange : UploadProps['onChange'] = (uploadFile: UploadFile) => {
  form.value.cover.push(uploadFile)
}
/**
 * 修改视频
 */
const changeVideoChange : UploadProps['onChange'] = (uploadFile: UploadFile) => {
  form.value.video.push(uploadFile)
}
/**
 * 删除封面
 */
const handleCoverRemove: UploadProps['onRemove'] = (uploadFile:UploadFile, uploadFiles:UploadFiles) => {
    form.value.cover = []
}
/**
 * 删除视频
 */
const handleVideoRemove = ():void => {
    form.value.video = []
}
const loadCategorys = ():void => {
  FileCategorys(FileType.Video).then((res:ServiceResponse<FileCategory[]>) => {
    categorys.value = res.data
  })
}
const handleSave = ():void => {
  isSubmit.value = true
  
  if(form.value.video.length === 0){
    ElMessage.error('请上传视频')
    isSubmit.value =false
    return
  }
  const formData = new FormData()
    formData.append('category',form.value.category.toString())
    formData.append('video', form.value.video[0].raw)
    if(form.value.cover.length > 0)
      formData.append('cover', form.value.cover[0].raw)
      UploadVideo(formData).then((res: ServiceResponse<FileEditor>) => {
      if(res.success) {
        if(res.data)
          emit('on-confirm', res.data)
        isSubmit.value = false
        ElMessage.success("上传成功")
      } else {
        ElMessage.error(res.msg)
        isSubmit.value =false
      }
        
    })
}
//定义事件
interface Emits {
    (e: 'update:visible', dialogVisible: boolean): void,
    (e: 'on-confirm', value: FileEditor ): void
}
const emit = defineEmits<Emits>()
//子组件不能修改Props值（通过get set解决）
const dialogVisible = computed({
    get() {
        return props.visible
    },
    set(visible: boolean) {
        emit('update:visible', visible)
    }
})
watch(() =>props.visible,(visible) => {
  if(visible) {
    form.value.category = props.category
    form.value.video =[]
    form.value.cover =[]
    loadCategorys()
  }
})
</script>
<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/formPage.scss";
::v-deep .el-upload-list__item-thumbnail {
  object-fit: scale-down;
}

.upload-max {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>